//
//  VideoCommentController.m
//  Otaku
//
//  Created by lanou3g on 16/5/11.
//  Copyright © 2016年 Liuwx. All rights reserved.
//

#import "VideoCommentController.h"
#import "LWX_VideoCommentCell.h"
#import "LWX_VideoCommentModel.h"
#import "LWX_VideoCell.h"
#import "VideoPlayView.h"

@interface VideoCommentController ()<VideoPlayViewDelegate,VideoTableViewCellDelegate,UMSocialUIDelegate,UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *myTableView;

@property (nonatomic, strong) NSMutableArray *recentCommentArray;
@property (nonatomic, strong) NSMutableArray *topCommentArray;
@property (nonatomic, strong) VideoPlayView *playView;
@property (nonatomic, strong) LWX_VideoCell *currentSelectedCell;
@property (nonatomic, assign) BOOL isFullScreenPlaying;


@end
static NSString *const resultID = @"CommentCell";
@implementation VideoCommentController





- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBar.translucent = NO;
    
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.navigationItem.title = @"评论详情";
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithTitle:@"视频" style:(UIBarButtonItemStylePlain) target:self action:@selector(backVideoAction:)];
    
    self.navigationItem.leftBarButtonItem = item;
    
    self.topCommentArray = [NSMutableArray new];
    self.recentCommentArray = [NSMutableArray new];
    [self loadDataWithComment];
    [self.myTableView registerNib:[UINib nibWithNibName:@"LWX_VideoCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    [self.myTableView registerNib:[UINib nibWithNibName:@"LWX_VideoCommentCell" bundle:nil] forCellReuseIdentifier:resultID];
    
    
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.playView.superview && self.isFullScreenPlaying == NO) {//点全屏和退出的时候，也会调用scrollViewDidScroll这个方法
        NSIndexPath *indePath = [self.myTableView indexPathForCell:self.currentSelectedCell];
        if (![self.myTableView.indexPathsForVisibleRows containsObject:indePath]) {//播放video的cell已离开屏幕
            [self.playView resetPlayView];
        }
    }
    
    if (self.myTableView.contentOffset.y>0) {
        self.navigationController.navigationBar.alpha = 1;
    } else {
        CGFloat yValue = - self.myTableView.contentOffset.y;//纵向的差距
        CGFloat alphValue = yValue/self.myTableView.contentInset.top;
        self.navigationController.navigationBar.alpha =alphValue;
    }
}

//
- (void)backVideoAction:(UIBarButtonItem *)item {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)loadDataWithComment {
    [LWXNetWorkRequestManager requestURL:[NSURL URLWithString:VIDEOCOMMENT_URL] Method:LWX_GET Params:@{@"group_id":self.groupID,@"item_id":@6423057152,@"count":@20,@"offset":@0,@"iid":@4240136140,@"device_id":@15036532241,@"ac":@"wifi",@"channel":@"ucad",@"aid":@7,@"app_name":@"joke_essay",@"version_code":@500,@"version_name":@"5.0.0",@"device_platform":@"android",@"ssmix":@"a",@"device_type":@"HUAWEI+B199",@"os_api":@18,@"os_version":@4.3,@"uuid":@"A000004F036FAC",@"openudid":@"e691cf971858edda",@"manifest_version_code":@500} Result:^(NSData *data, NSURLResponse *response, NSError *error) {
            if (data) {
            
            NSMutableDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSDictionary *dataDict = jsonDict[@"data"];
            
            for (NSDictionary *itemDict in dataDict[@"recent_comments"]) {
                LWX_VideoCommentModel *model = [LWX_VideoCommentModel new];
                
                [model setValuesForKeysWithDictionary:itemDict];
                [self.recentCommentArray addObject:model];
                
            }
            for (NSDictionary *itemDict in dataDict[@"top_comments"]) {
                LWX_VideoCommentModel *model = [LWX_VideoCommentModel new];
                [model setValuesForKeysWithDictionary:itemDict];
                [self.topCommentArray addObject:model];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.myTableView reloadData];
                
            });
            
        }
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 3;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    switch (section) {
        case 0: {
            
            return self.videoTitle;
        }
            break;
        case 1:
            return @"热门评论";
            break;
        case 2:
            return @"最新评论";
            break;
            
        default:
            break;
    }
    
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return self.cellHeight;
    }
    if(indexPath.section == 1){
        LWX_VideoCommentModel *model = self.topCommentArray[indexPath.row];
        
        return model.cellHeight;
    }
    
    if (indexPath.section == 2) {
        LWX_VideoCommentModel *model = self.recentCommentArray[indexPath.row];
        return model.cellHeight;
        
    }
    
    return 0;
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    if (self.isFullScreenPlaying == NO) {
        [self.playView resetPlayView];
        
    }
    self.navigationController.navigationBar.alpha = 1;
}

#pragma mark VideoTableViewCell的代理方法
- (void)clickVideoButton:(NSIndexPath *)indexPath {
    
    [self.playView resetPlayView];
    LWX_VideoCell *cell = [self.myTableView cellForRowAtIndexPath:indexPath];
    self.currentSelectedCell = cell;
    VideoPlayView *playView = [VideoPlayView videoPlayView];
    
    LWX_VideoModel *model = self.videoArray[self.index];
    playView.frame = model.videoFrame;
    [cell addSubview:playView];
    cell.playView = playView;
    self.playView = playView;
    self.playView.delegate = self;
    
    AVPlayerItem *item = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:model.mp4_url]];
    self.playView.playerItem = item;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }else if (section == 1) {
        return self.topCommentArray.count;
    }else {
        return self.recentCommentArray.count;
    }
    return 0;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        LWX_VideoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        cell.model = self.videoArray[self.index];
        cell.indexPath = indexPath;
        cell.delegate = self;
        [cell.shareBtn addTarget:self action:@selector(shareBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
    
    if (indexPath.section == 1) {
        LWX_VideoCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:resultID forIndexPath:indexPath];
        cell.model = self.topCommentArray[indexPath.row];
        return cell;
        
    }
    if (indexPath.section == 2) {
        LWX_VideoCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:resultID forIndexPath:indexPath];
        cell.model = self.recentCommentArray[indexPath.row];
        return cell;
    }
    return nil;
}

// 分享事件
- (void)shareBtnAction:(UIButton *)btn {
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"572c6a8ce0f55ac72d000352"
                                      shareText:@"分享的文字"
                                     shareImage:[UIImage imageNamed:@"icon"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,nil]
                                       delegate:self];
  
    [UMSocialData defaultData].extConfig.title = self.model.text;
    [UMSocialData defaultData].shareText = [NSString stringWithFormat:@"%@+%@",self.model.text,self.model.share_url];
 
}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 } else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

/*
 #pragma mark - Table view delegate
 
 // In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
 // Navigation logic may go here, for example:
 // Create the next view controller.
 <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:<#@"Nib name"#> bundle:nil];
 
 // Pass the selected object to the new view controller.
 
 // Push the view controller.
 [self.navigationController pushViewController:detailViewController animated:YES];
 }
 */

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
